package net.zhengxinyun.performance.service.login;

import com.alibaba.druid.sql.visitor.functions.If;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.data.EvaluateUserData;
import net.zhengxinyun.performance.entity.DepartmentEntity;
import net.zhengxinyun.performance.entity.EvaluateUserEntity;
import net.zhengxinyun.performance.filter.EvaluateUserFilter;
import net.zhengxinyun.performance.mapper.Department.DepartmentEntityMapper;
import net.zhengxinyun.performance.mapper.login.EvaluateUserEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by hyp1202 on 2018/12/17.
 */
@Service
public class EvaluateUserServiceImpl implements EvaluateUserService {

    @Value("${path}")
    public  String PATH ;

    private EvaluateUserEntityMapper evaluateUserEntityMapper;

    private EvaluateUserData evaluateUserData;

    @Autowired
    private DepartmentEntityMapper departmaper;

    @Autowired
    public EvaluateUserServiceImpl(EvaluateUserData evaluateUserData, EvaluateUserEntityMapper evaluateUserEntityMapper) {
        this.evaluateUserData = evaluateUserData;
        this.evaluateUserEntityMapper = evaluateUserEntityMapper;
    }

    public void setEvaluateUserEntityMapper(EvaluateUserEntityMapper evaluateUserEntityMapper) {
        this.evaluateUserEntityMapper = evaluateUserEntityMapper;
    }

    public EvaluateUserData getEvaluateUserData() {
        return evaluateUserData;
    }

    public void setEvaluateUserData(EvaluateUserData evaluateUserData) {
        this.evaluateUserData = evaluateUserData;
    }

    @Override
    public String insert(EvaluateUserEntity evaluateUserEntity) {
        int i = evaluateUserEntityMapper.insert(evaluateUserEntity);
        if (i == 0){
            return "添加失败，请重试";
        }
        return "添加成功";
    }

    @Override
    public String update(EvaluateUserEntity evaluateUserEntity) {
        int i = evaluateUserEntityMapper.updateByPrimaryKeySelective(evaluateUserEntity);
        if (i == 0){
            return "修改失败，请重试";
        }
        return "修改成功";
    }

    @Override
    @Transactional
    public String delete(List<String> list) {
        for (String entity:list) {
            int i = evaluateUserEntityMapper.deleteByPrimaryKey(Long.valueOf(entity));
            if (i == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "批量删除失败，请重试";
            }
        }
        return "删除成功";
    }

    @Override
    public List<EvaluateUserFilter> query(EvaluateUserFilter evaluateUserFilter) {
        return evaluateUserEntityMapper.query(evaluateUserFilter);
    }

    @Override
    public List<EvaluateUserFilter> queryAll(EvaluateUserFilter evaluateUserFilter) {
        return evaluateUserEntityMapper.queryAll(evaluateUserFilter);
    }

    @Override
    public Integer queryForCount(EvaluateUserFilter evaluateUserFilter) {
        return evaluateUserEntityMapper.queryForCount(evaluateUserFilter);
    }

    @Override
    public HashMap<String,Object> importEvaluateUser(MultipartFile file) {

        HashMap<String,Object> map = new HashMap<>();

        if (file.getOriginalFilename().endsWith(".xls") == false && file.getOriginalFilename().endsWith(".xlsx") == false) {
            map.put("code",500);
            map.put("msg","文件后缀错误，请重新上传");
            return map;
        }
        String filePath;
        try {
            Util.write(file.getOriginalFilename(), file.getInputStream());
            filePath = this.PATH + file.getOriginalFilename();
            filePath = new String(filePath.getBytes("utf-8"), "utf-8");
            if (StringUtils.isBlank(filePath)) {

                map.put("code",500);
                map.put("msg","上传失败");
                return map;
                //return "filePath为空";
            }
            List<EvaluateUserEntity> list = evaluateUserData.importEvaluateUser(filePath);

            List<String> error = new ArrayList<>();
            for (EvaluateUserEntity entity : list) {
                String matchDepart = matchDepart(entity.getDepartment());
                if("error".equals(matchDepart))
                {
                    error.add(entity.getName()+"部门或者单位匹配错误，请修改后重新上传");
                }else {
                    entity.setDepartCode(matchDepart);
                }

            }

            if(error.size()>0)
            {
                map.put("code",500);
                map.put("msg","单位匹配失败");
                map.put("error",error);
                return map;
            }

            for (EvaluateUserEntity entity:list) {


                int i = evaluateUserEntityMapper.insert(entity);

                if (i == 0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    map.put("code",500);
                    map.put("msg","上传失败！");
                    map.put("error",error);
                    return map;
                }
            }
            map.put("code",200);

            File fileDel = new File(filePath);
            if(fileDel.exists()&&fileDel.isFile())
            {
                fileDel.delete();
            }

            return map;
        }catch (Exception e) {
            map.put("code",500);
            return map;
        }
    }


    /**
     * 匹配单位
     * @param departName
     * @return
     */
    public String  matchDepart(String departName) {

        DepartmentEntity departmentEntity = null;

        if (net.zhengxinyun.performance.Util.StringUtils.isNotBlank(departName)) {
            departmentEntity = departmaper.getDepartByName(departName);
        }


        if (ObjectUtils.isNotBlank(departmentEntity)) {
            return departmentEntity.getDepartcode();
        } else {
            return "error";
        }


    }


    @Override
    public EvaluateUserEntity selectById(Long id) {

        return  evaluateUserEntityMapper.selectByPrimaryKey(id);
    }
}
